package com.webserver.core;

import com.webserver.http.HttpServletRequest;
import com.webserver.http.HttpServletResponse;

import java.io.File;
import java.net.URISyntaxException;

/**
 * 用于处理请求
 */
public class DispatcherServlet {
    private static File root;
    private static File staticDir;
    static {
        try {
            root = new File(DispatcherServlet.class.getClassLoader().getResource(".").toURI());
            staticDir = new File(root,"static");
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }

    }

    public void service(HttpServletResponse response, HttpServletRequest request){
        String path = request.getUri();//path: /myweb/index.html
        File file = new File(staticDir,path);
        System.out.println("页面是否存在: "+file.exists());
        if (file.isFile()){
            response.setContentFile(file);
        }else {
            response.setStatusCode(404);
            response.setStatusReason("NotFound");
            file = new File(staticDir,"root/404.html");
            response.setContentFile(file);
        }
    }
}
